<script setup lang="ts">
import type { DictItem, DictSelectProps, DictSelectEmits } from './types';

import { computed, onMounted, ref, watch } from 'vue';
import { Select } from 'ant-design-vue';
import { message } from 'ant-design-vue';

import { getDictionary2 } from '../../api/core/setting';

defineOptions({
  name: 'DictSelect',
});

const props = withDefaults(defineProps<DictSelectProps>(), {
  multiple: false,
  placeholder: '请选择',
  disabled: false,
  allowClear: true,
  size: 'middle',
  showSearch: false,
  filterOption: true,
  maxTagCount: 3,
  listHeight: 256,
  autoLoad: true,
  width: 120,
});

const emit = defineEmits<DictSelectEmits>();

// 内部状态
const loading = ref(false);
const options = ref<DictItem[]>([]);
const internalValue = ref(props.value);

// 计算属性
const selectProps = computed(() => {
  const {
    dictType,
    customApi,
    autoLoad,
    ...restProps
  } = props;
  return restProps;
});

// 监听外部value变化
watch(
  () => props.value,
  (newValue) => {
    internalValue.value = newValue;
  },
  { immediate: true }
);
/**
 * 加载字典数据
 */
const loadDictData = async () => {
  if (!props.dictType) {
    console.warn('DictSelect: dictType is required');
    return;
  }

  try {
    loading.value = true;
    let dictData: DictItem[] = [];

    if (props.customApi) {
      // 使用自定义API
      dictData = await props.customApi(props.dictType);
    } else {
      // 使用默认API
      const response = await getDictionary2(1, 1000, props.dictType);
      console.log(response);
      if (response.data && Array.isArray(response.data)) {
        dictData = response.data.map((item: any) => ({
          value:item.describes,
          label:item.describes,
          // value: item.value || item.id,
          // label: item.label || item.name || item.dictLabel,
          // description: item.description || item.remark,
          // disabled: item.disabled || item.status === '0',
          // ...item,
        }));
      }
    }

    options.value = dictData;
  } catch (error) {
    console.error('Failed to load dictionary data:', error);
    message.error('加载字典数据失败');
    options.value = [];
  } finally {
    loading.value = false;
  }
};
// 监听dictType变化，重新加载数据
watch(
  () => props.dictType,
  (newDictType) => {
    if (newDictType && props.autoLoad) {
      loadDictData();
    }
  },
  { immediate: true }
);



/**
 * 值变化处理
 */
const handleChange = (value: any, option: any) => {
  internalValue.value = value;
  emit('update:value', value);
  emit('change', value, option);
};

/**
 * 搜索处理
 */
const handleSearch = (value: string) => {
  emit('search', value);
};

/**
 * 下拉框展开/收起处理
 */
const handleDropdownVisibleChange = (open: boolean) => {
  emit('dropdownVisibleChange', open);
};

/**
 * 手动刷新数据
 */
const refresh = () => {
  loadDictData();
};

/**
 * 清空选择
 */
const clear = () => {
  const newValue = props.multiple ? [] : '';
  internalValue.value = newValue;
  emit('update:value', newValue);
  const optionValue = props.multiple ? [] : { value: '', label: '' };
  emit('change', newValue, optionValue);
};

// 组件挂载时加载数据
onMounted(() => {
  if (props.dictType && props.autoLoad) {
    loadDictData();
  }
});

// 暴露方法给父组件
defineExpose({
  refresh,
  clear,
  loadDictData,
});
</script>

<template>
  <a-select
    v-model="internalValue"
    :loading="loading"
    :options="options"
    :field-names="{ label: 'label', value: 'value' }"
    :mode="props.multiple ? 'multiple' : undefined"
    :placeholder="props.placeholder"
    :disabled="props.disabled"
    :allow-clear="props.allowClear"
    :size="props.size"
    :show-search="props.showSearch"
    :max-tag-count="props.maxTagCount"
    :list-height="props.listHeight"
    :style="{ width: props.width + 'px' }"
    @change="handleChange"
    @search="handleSearch"
    @dropdown-visible-change="handleDropdownVisibleChange"
  >
    <!-- 自定义选项插槽 -->
    <template #option="{ label, description, disabled }">
      <div class="dict-option" :class="{ 'dict-option--disabled': disabled }">
        <div class="dict-option__label">{{ label }}</div>
        <div v-if="description" class="dict-option__description">
          {{ description }}
        </div>
      </div>
    </template>

    <!-- 自定义标签渲染（多选时） -->
    <template #tagRender="{ label, closable, onClose }">
      <a-tag
        :closable="closable"
        class="dict-tag"
        @close="onClose"
      >
        {{ label }}
      </a-tag>
    </template>

    <!-- 空状态 -->
    <template #notFoundContent>
      <div class="dict-empty">
        <div class="dict-empty__text">暂无数据</div>
      </div>
    </template>
  </a-select>
</template>

<style lang="scss" scoped>
.dict-option {
  padding: 4px 0;
  
  &--disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
  
  &__label {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
  }
  
  &__description {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);
    margin-top: 2px;
  }
}

.dict-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.dict-empty {
  padding: 20px;
  text-align: center;
  
  &__text {
    color: rgba(0, 0, 0, 0.45);
    font-size: 14px;
  }
}

:deep(.ant-select-dropdown) {
  .ant-select-item-option {
    padding: 8px 12px;
  }
}
</style>